/**
 * 功能:TK_MATERIAL_ALLOCATES 控制器类
 * 开发人员:chengd
 * 创建时间:2012/4/23 17:56:16
 */
package com.towker.frame.controller.warehouse;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.towker.web.MyRequest;
import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.core.util.StringUtil;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Goods;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.warehouse.GoodsAllocates;
import com.towker.frame.model.warehouse.MaterialAllocates;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.model.warehouse.WarehouseAccounts;
import com.towker.frame.service.basicData.CustomsService;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.basicData.DepotsService;
import com.towker.frame.service.basicData.GoodsService;
import com.towker.frame.service.basicData.SurplusOrderService;
import com.towker.frame.service.sell.RefGoodsService;
import com.towker.frame.service.warehouse.MaterialAllocatesService;
import com.towker.frame.service.warehouse.WarehouseAccountsService;
import com.towker.frame.share.sys.user.UserShare;

//TK_MATERIAL_ALLOCATES
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/warehouse")
public class MaterialAllocatesController extends BaseController
{
	private MaterialAllocatesService service;
	private CustomsService customsService;//客户信息
	private DepartmentsService departmentsService;//部门信息
	private DepotsService depotsService;//仓库信息
	private GoodsService goodsService;//物品信息
	private WarehouseAccountsService warehouseAccountsService;
	private SurplusOrderService surplusOrderService;

	//业务对象注入
	public void setMaterialAllocatesService(MaterialAllocatesService service)
	{
		this.service = service;
	}
	public void setCustomsService(CustomsService customsService)
	{
		this.customsService = customsService;
	}
	
	public void setDepartmentsService(DepartmentsService departmentsService)
	{
		this.departmentsService = departmentsService;
	}
	
	public void setDepotsService(DepotsService depotsService)
	{
		this.depotsService = depotsService;
	}
	
	public void setGoodsService(GoodsService goodsService)
	{
		this.goodsService = goodsService;
	}
	
	public void setWarehouseAccountsService(WarehouseAccountsService warehouseAccountsService)
	{
		this.warehouseAccountsService = warehouseAccountsService;
	}
	
	public void setSurplusOrderService(SurplusOrderService surplusOrderService) {
		this.surplusOrderService = surplusOrderService;
	}

	//添加
	@RequestMapping("/addMaterialAllocates{viewName}")
	public ModelAndView addMaterialAllocates(HttpServletResponse response, HttpServletRequest request ,MaterialAllocates po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map = new HashMap();
			List customsList = customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));// 客户信息
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("customsList", customsList);
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("mallocate_code", service.getNewMallocateCode());//原材料调拨单号
			result.setViewName("/manage/warehouse/addMaterialAllocates.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				po.setCreater_code(UserShare.getCurrentUserCode(request)+"["+UserShare.getCurrentUserName(request)+"]");//获取当前用户代码 名称
				po.setCreater_id(UserShare.getCurrentUserId(request).intValue());//获取当前用户id
				
				po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
				//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
				
				service.add(po);
				MyRequest myRequest = new MyRequest(request);
				String goodsInfo = myRequest.getString("goodsInfo");
				processRefGoods(request, RefGoodsType.MATERIALLOCATES_GOODS, po.getId(), goodsInfo);
				//处理库存量,减少
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(),po.getId() );

				calcGoodsStock(new ArrayList<RefGoods>(), refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), false, true);
				
				writer.write("添加仓库原材料调拨单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加仓库原材料调拨单失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delMaterialAllocates")
	public void delMaterialAllocates(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		long[] ids = req.getLongArray("keyIndex", 0);
		
		for (Long id : ids) {
			MaterialAllocates w = service.getById(id);
			if (w != null) {
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(), id.intValue());
				calcGoodsStock(refOldGoods, new ArrayList<RefGoods>(), surplusOrderService, w.getDepot_code(), w.getAuthCoCode(), false, true);
			}
		}
		service.delByIds(CollectionUtil.toLongArray(ids));
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updMaterialAllocates{viewName}")
	public ModelAndView updMaterialAllocates(HttpServletRequest request, HttpServletResponse response, MaterialAllocates po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			Long id = req.getLong("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			result.addObject("po", po);
			Map map = new HashMap();
			List customsList = customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));// 客户信息
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("customsList", customsList);
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(),new Integer(String.valueOf(id)) ));
			result.setViewName("/manage/warehouse/updMaterialAllocates.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			String goodsInfo = req.getString("goodsInfo");
			try
			{
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(),po.getId() );
				service.update(po);
				processRefGoods(request, RefGoodsType.MATERIALLOCATES_GOODS, po.getId(), goodsInfo);
				//处理库存量,减少
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(),po.getId() );

				calcGoodsStock(refOldGoods, refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), false, true);
				
				writer.write("修改仓库原材料调拨单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改仓库原材料调拨单失败！" + e.getCause());
			}
		}
		return result;
	}

	//获得分页
	@RequestMapping("/getMaterialAllocates")
	public ModelAndView getMaterialAllocates(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<MaterialAllocates> pageModel = service.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.setViewName("/manage/warehouse/getMaterialAllocates.jsp");
		return result;
	}

	//明细
	@RequestMapping("/getMaterialAllocatesById")
	public ModelAndView getMaterialAllocatesById(HttpServletRequest request, HttpServletResponse response)
	{
		MaterialAllocates po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		result.addObject("dep", departmentsService.getByCode(po.getDep_code()));
		result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
		result.addObject("custom_name", customsService.getCustomName(false, 0, po.getCustom_code()));
		result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		result.setViewName("/manage/warehouse/getMaterialAllocatesById.jsp");
		return result;
	}
	
	
	//审核
	@RequestMapping("/auditMaterial{viewName}")
	public ModelAndView auditMaterial(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName)throws IOException
	{
		ModelAndView result = null;;
		MaterialAllocates po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			result.addObject("audit", "audit");
			result.addObject("po", po);
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(),new Integer(String.valueOf(id)) ));
			result.setViewName("/manage/warehouse/getMaterialAllocatesById.jsp");
			
		}else if ("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try
			{
				//审核人员ID
				//审核人员代码
				//审核状态
				po.setAudit_status(1);
				service.update(po);
				writer.write("审核成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("审核失败！" + e.getCause());
			}
		}
		return result;
	}
	
	
	/*//记账
	@RequestMapping("/accMaterial{viewName}")
	public ModelAndView accMaterial(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName)throws IOException
	{
		ModelAndView result = null;
		MaterialAllocates po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			result.addObject("acc","acc");
			result.addObject("po", po);
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(),new Integer(String.valueOf(id)) ));
			result.setViewName("/manage/warehouse/getMaterialAllocatesById.jsp");
			
		}else if ("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try
			{
				//添加数据到仓库帐中
				po.setAcc_status(1);
				service.update(po);
				
				List<RefGoods> refgoodList = refGoodsService.getByInfoType(RefGoodsType.MATERIALLOCATES_GOODS.getValue(), po.getId());
				if (refgoodList!=null && refgoodList.size()!=0) {
					for (int i = 0; i < refgoodList.size(); i++) {
						*//**
						 * 减少库存数量
						 *//*
						RefGoods refGoods = (RefGoods)refgoodList.get(i);
						Goods goods = goodsService.getById(new Long(refGoods.getGoods_id()));
						//更新库存数量
						double stock = goods.getStock()-refGoods.getAmount();
						goods.setStock(stock);
						goodsService.update(goods);
						*//**
						 * 记录到仓库帐中
						 *//*
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						WarehouseAccounts warehouseAccounts = new WarehouseAccounts();
						warehouseAccounts.setAcc_period(po.getAcc_period());//财务统计核算期
						warehouseAccounts.setInfo_type("原材料调拨单");//仓库帐类型
						warehouseAccounts.setGoods_sn(goods.getGoods_sn());//物料代码
						warehouseAccounts.setDep_code(po.getDepot_code());//仓库代码
						warehouseAccounts.setCreate_date(po.getOut_date());//日期
						warehouseAccounts.setCreate_time(po.getOut_time());//时间
						warehouseAccounts.setSys_date(format.format(new Date()));//生成仓库帐时间
						warehouseAccounts.setAmount(refGoods.getAmount());//物品数量
						warehouseAccounts.setStock_num(stock);//当前库存数量
						//warehouseAccounts.setSend_amount(0);//已下采购单要求送货数量, 根据采购单号 查询采购数量
						String remark = "单号："+po.getMallocate_code()+"，部门："+po.getDep_code()+"";
						warehouseAccounts.setRemark(remark);//凭证号（单号）、部门、客户等>
						warehouseAccountsService.add(warehouseAccounts);
					}
				}
				
				writer.write("记账成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("记账失败！" + e.getCause());
			}
		}
		return result;
	}*/
}
